package com.shuaigequtan.config;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.reactive.DefaultResponse;
import org.springframework.cloud.client.loadbalancer.reactive.EmptyResponse;
import org.springframework.cloud.client.loadbalancer.reactive.Request;
import org.springframework.cloud.client.loadbalancer.reactive.Response;
import org.springframework.cloud.loadbalancer.core.ReactorServiceInstanceLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Random;

public class MyRandomClient implements ReactorServiceInstanceLoadBalancer {
    // 服务列表
    private ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider;

    public MyRandomClient(ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider) {
        this.serviceInstanceListSupplierProvider = serviceInstanceListSupplierProvider;
    }

    @Override
    public Mono<Response<ServiceInstance>> choose(Request request) {
        return null;
    }

        /**
         * 使用随机数获取服务
         * @param instances
         * @return
         */
        private Response<ServiceInstance> getInstanceResponse(
                List<ServiceInstance> instances) {
            System.out.println("进来了");
            if (instances.isEmpty()) {
                return new EmptyResponse();
            }

            System.out.println("进行随机选取服务");
            // 随机算法
            int size = instances.size();
            Random random = new Random();
            ServiceInstance instance = instances.get(random.nextInt(size));

            return new DefaultResponse(instance);
        }
}
